/**
 * 
 */
package com.m7012e.a_remote.ar_listeners.network.protocol;

import java.io.IOException;
import java.net.UnknownHostException;

import com.leoj.utils.Handler;
import com.m7012e.a_remote.ar_listeners.exception.WrongMessageProtocolException;
import com.m7012e.a_remote.commons.ARemoteTcpSender;
import com.m7012e.a_remote.commons.IncomingMulticastMessage;
import com.m7012e.a_remote.communication.DisplayDiscoveryMessage;
import com.m7012e.a_remote.communication.Message;
import com.m7012e.a_remote.communication.positioning.Position;
import com.m7012e.a_remote.communication.positioning.SimplePosition;
import com.m7012e.a_remote.communication.tcpMessages.EvaluatedDistanceMessage;
import com.m7012e.a_remote.communication.tcpMessages.NotAvailableMessage;

/**
 * @author leoj
 *
 */
public class MulticastProtocol implements Handler<IncomingMulticastMessage>{
	private DaemonProtocolFactory _daemonState;
	private Position _daemonPosition;
	private String _daemonAddress;
	private int _daemonPort;
	/**
	 * 
	 */
	public MulticastProtocol(DaemonProtocolFactory daemonState, Position position, String daemonAddress, int daemonPort) {
		_daemonState = daemonState;
		_daemonAddress = daemonAddress;
		_daemonPort = daemonPort;
		_daemonPosition = position;
	}

	/* (non-Javadoc)
	 * @see com.leoj.utils.Handler#handle(java.lang.Object)
	 */
	@Override
	public void handle(IncomingMulticastMessage args) {
		Message msg = args.msg;
		
		if(!(msg instanceof DisplayDiscoveryMessage)){
			throw new WrongMessageProtocolException();
		}
		DisplayDiscoveryMessage discoverMsg = (DisplayDiscoveryMessage) msg;
		int distance = discoverMsg.remotePosition.compareTo((SimplePosition)_daemonPosition);
		System.out.println("multicastprotocol is about to answer to a remote :");
		System.out.println("daemon -> @"+_daemonAddress+":"+_daemonPort);;
//		System.out.println("remote -> @"+discoverMsg.remoteAddress+":"+discoverMsg.remotePort);
		System.out.println("remote -> @"+args.remoteAddress.getHostAddress()+":"+discoverMsg.remotePort);
		if(_daemonState.isAvailable()){
			try {
				ARemoteTcpSender.sendMessage(new EvaluatedDistanceMessage(_daemonAddress, _daemonPort, distance), args.remoteAddress.getHostAddress(), discoverMsg.remotePort);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				ARemoteTcpSender.sendMessage(new NotAvailableMessage(distance), args.remoteAddress.getHostAddress(), discoverMsg.remotePort);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
